import React from 'react'
import { View, Text, Image, Picker, ScrollView } from '@tarojs/components'
import { AtTextarea, AtButton, AtInputNumber, AtFab, AtFloatLayout, AtActivityIndicator, AtCountdown } from 'taro-ui'
import Taro from '@tarojs/taro'
import './index.scss'
import { DeviceList } from '../../serverless/deviceList'
import { DescribeTaskStatus, WeMqttApi } from '../../serverless/weMqttApi'
import { dateReplace, formatDate } from '../../uilts/util'
import { LedTask, LedTaskExecutedStatus } from '../../serverless/LedTask'
import { IMAGES } from '../../uilts/images'


function MinutesCeil(minutes: number) {
  return Math.ceil(minutes / 10) * 10
}
function b0(num: number) {
  return num.toString().length === 1 ? `0${num}` : num
}
function GetSelectorHour() {
  return new Array(24).fill(0).map((_x, i) => b0(i))
}
function GetSelectorMinutes() {
  return new Array(6).fill(0).map((_x, i) => b0(i * 10))
}


export default class Index extends React.Component {

  state = {
    loading: false,
    deviceInfo: {} as DeviceList,
    ledTasks: [] as LedTask[],
    AtFloatLayoutIsOpened: false,
    ledtext: '',
    speed: 50,
    count: 0,
    changeDate: formatDate(new Date()).date2,
    changeTime: formatDate(new Date()).time3,
    changeHour: new Date().getHours(),
    changeMinutes: MinutesCeil(new Date().getMinutes()),
    selectorHour: GetSelectorHour(),
    selectorMinutes: GetSelectorMinutes(),
  }

  async componentWillMount() {
    try {
      if (!DeviceList.globalDeviceList) throw new Error('未找到设备')
      this.setState({
        deviceInfo: DeviceList.globalDeviceList,
      }, () => {
        this.getLedTask()
      })
    } catch (error) {
      Taro.showModal({
        title: '加载设备信息失败',
        content: error.message,
        showCancel: false
      })
    }
  }


  private LedTaskOnGetting: boolean = false;
  async getLedTask() {
    try {
      const { deviceInfo } = this.state
      if (this.LedTaskOnGetting) return
      this.setState({ loading: true })
      this.LedTaskOnGetting = true
      const a = await LedTask.GetLedTask(deviceInfo)
      for (let index = 0; index < a.length; index++) {
        const element = a[index];
        if (element.executedStatus === LedTaskExecutedStatus.CreateTaskSuccess) {
          const b = new WeMqttApi(deviceInfo.info.deviceId)
          const c = await b.describeTask(element.get_id())
          console.log(c);
          if (c.data?.Status === DescribeTaskStatus.Completed) {
            await element.setExecutedStatus(LedTaskExecutedStatus.Success)
          }
        }
      }
      this.setState({
        ledTasks: a,
      })
    } catch (error) {
      Taro.showModal({
        title: '加载任务失败',
        content: error.message,
        showCancel: false
      })
    }
    this.LedTaskOnGetting = false
    this.setState({ loading: false })
  }


  handleChange(key: string, value: any) {
    this.setState({
      [key]: value
    })
  }

  async onCreateLedTaskText() {
    try {
      const { speed, count, ledtext, changeDate, deviceInfo, changeTime } = this.state

      const time = new Date(`${dateReplace(changeDate)} ${changeTime}:00 GMT+0800`).getTime()
      const now = new Date().getTime()
      console.log({
        time,
        now
      });

      if (now > time) throw new Error('无法为您设定的时间更新，除非有时光鸡。')
      if (ledtext.length === 0) throw new Error('至少也写点东西让我更新吧。')
      Taro.showLoading({ title: "添加中" })
      const a = await LedTask.CreateLedTaskText(deviceInfo, ledtext, speed, count, time)
      const b = new WeMqttApi(deviceInfo.info.deviceId)
      const c = await b.createLedTaskText(a._id.toString())
      console.log(a);
      console.log(c);
      this.setState({ AtFloatLayoutIsOpened: false })
      this.getLedTask()
    } catch (error) {
      console.error(error);

      Taro.showModal({
        title: '添加失败',
        content: error.message,
        showCancel: false
      })
    }
    Taro.hideLoading()
  }


  addView() {
    const { speed, count, ledtext, changeDate, changeTime } = this.state
    return <View>
      {/* 更换日期 */}
      <View className='at-row mag-top speed'>
        <View className='at-col at-col-6 at-col__offset-1 '>
          <View><Text className='ledtext-title title'>更换日期</Text></View>
        </View>
        <View className='at-col at-col-3 center-horizontally' >
          <View>
            <Picker value={changeDate} mode="date" onChange={(e) => this.handleChange('changeDate', e.detail.value)}>
              {changeDate}
            </Picker>
          </View>
        </View>
      </View>
      {/* 更换时间 */}
      <View className='at-row mag-top speed'>
        <View className='at-col at-col-6 at-col__offset-1 '>
          <View><Text className='ledtext-title title'>更换时间</Text></View>
        </View>
        <View className='at-col at-col-3 center-horizontally' >
          <View>
            <Picker value={changeTime} mode="time" onChange={(e) => this.handleChange('changeTime', e.detail.value)}>
              {changeTime}
            </Picker>
          </View>
        </View>
      </View>
      {/* 轮播速度 */}
      <View className='at-row mag-top speed'>
        <View className='at-col at-col-4 at-col__offset-1 '>
          <View><Text className='ledtext-title title'>轮播速度</Text></View>
          <View><Text className='ledtext-title tisp'>选值20-50，数值越小速度越快</Text></View>
        </View>
        <View className='at-col at-col-6 center-horizontally justify-content-flex-end' >
          <AtInputNumber
            type='number'
            disabledInput
            width={150}
            min={20}
            max={50}
            step={5}
            value={speed}
            onChange={this.handleChange.bind(this, "speed")}
          />
        </View>
      </View>
      {/* 轮播次数 */}
      <View className='at-row mag-top speed'>
        <View className='at-col at-col-4 at-col__offset-1 '>
          <View><Text className='ledtext-title title'>轮播次数</Text></View>
          <View><Text className='ledtext-title tisp'>选值0-99999，0则无限循环</Text></View>
        </View>
        <View className='at-col at-col-6 center-horizontally justify-content-flex-end' >
          <AtInputNumber
            type='number'
            width={150}
            min={0}
            max={99999}
            step={50}
            value={count}
            onChange={this.handleChange.bind(this, "count")}
          />
        </View>
      </View>
      {/* 输入框 */}
      <View className='at-row mag-top'>
        <View className='at-col at-col-10 at-col__offset-1'>
          <AtTextarea
            value={ledtext}
            onChange={this.handleChange.bind(this, 'ledtext')}
            maxLength={200}
            placeholder='请输入轮播的文本...'
          />
        </View>
      </View>
      {/* 输入框 */}
      <View className='at-row mag-top'>
        <View className='at-col at-col-10 at-col__offset-1'>
          <AtButton type='primary' onClick={this.onCreateLedTaskText.bind(this)}>添加</AtButton>
        </View>
      </View>
    </View>
  }


  ledTasksView() {
    const { ledTasks } = this.state
    return ledTasks.map((x, i) => {
      const now = new Date().getTime() / 1000;
      const time = x.changeTime.getTime() / 1000;
      const seconds = time - now;
      return <View key={i} className='at-row led-tasks-view'>
        <View className='at-col at-col-10 at-col__offset-1'>
          <View className='at-row'>
            {/* 图标 */}
            <View className='at-col at-col-2'>
              {x.executedStatus === LedTaskExecutedStatus.Wait && <View className='at-icon at-icon-clock led-tasks-view-icon'></View>}
              {x.executedStatus === LedTaskExecutedStatus.CreateTaskSuccess && <View className='at-icon at-icon-clock led-tasks-view-icon'></View>}
              {x.executedStatus === LedTaskExecutedStatus.Success && <View className='at-icon at-icon-check-circle led-tasks-view-icon'></View>}
            </View>
            <View className='at-col at-col-8'>
              <AtCountdown
                isCard={true}
                isShowDay={true}
                seconds={seconds}
              />
            </View>
            <View className='at-col at-col-2'></View>
          </View>
          <View className='at-row led-tasks-view-info'>
            <View className='at-col at-col-10 at-col__offset-2'>
              {/* 轮播内容 */}
              <View className='at-row'>
                <View className='at-col at-col-4 title'>轮播内容</View>
                <View className='at-col at-col-8 view-white-space'>{x.ledtext}</View>
              </View>
              {/* 轮播速度 */}
              <View className='at-row'>
                <View className='at-col at-col-4 title'>轮播速度</View>
                <View className='at-col at-col-8 view-white-space'>{x.speed}</View>
              </View>
              {/* 轮播次数 */}
              <View className='at-row'>
                <View className='at-col at-col-4 title'>轮播次数</View>
                <View className='at-col at-col-8 view-white-space'>{x.count}</View>
              </View>
            </View>
          </View>
        </View>
      </View>
    })
  }

  render() {
    const { ledTasks, AtFloatLayoutIsOpened, loading } = this.state

    return (
      <View className='index guide'>
        <AtFab className='fab-btn' onClick={() => this.setState({ AtFloatLayoutIsOpened: true })}>
          <Text className='at-fab__icon at-icon at-icon-add'></Text>
        </AtFab >
        <AtFloatLayout className='at-float-layout' isOpened={AtFloatLayoutIsOpened} title="任务添加" onClose={() => this.setState({ AtFloatLayoutIsOpened: false })}>
          <View className='at-row'>
            <View className='at-col at-col-12'>
              {AtFloatLayoutIsOpened && this.addView()}
            </View>
          </View>
        </AtFloatLayout>
        {loading === true && <View>
          <View className='loading center-horizontally'>
            <AtActivityIndicator content='加载中...'></AtActivityIndicator>
          </View>
        </View>}
        {loading === false && <View>
          {ledTasks.length === 0 && <View>
            <View className='center-horizontally'>
              <Image className='image-empty' src={IMAGES.empty} />
            </View>
            <View className='center-horizontally'>
              <View className='text-empty'>空空如也，右下方添加任务</View>
            </View>
          </View>}
          {ledTasks.length > 0 && <View>
            {this.ledTasksView()}
          </View>}
        </View>}
      </View >
    )
  }
}
